package com.guochenglang.www.service.impl;

import com.guochenglang.www.dao.FilesDao;
import com.guochenglang.www.dao.impl.FilesDaoImpl;
import com.guochenglang.www.pojo.Files;
import com.guochenglang.www.service.FileService;
import com.guochenglang.www.util.MyDependency;
import com.guochenglang.www.web.result.Result;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.io.FilenameUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

/**
 * 打印普通字段到控制台
 *
 * @author 郭程朗
 */
public class FileServiceImpl implements FileService {
    private static final FilesDao FILES_DAO = new FilesDaoImpl();

    /**
     * 处理非附件字段，获取非附件字段的id
     *
     * @param item 前端获取的非文件的item字段
     * @return 非附件字段的id
     */
    @Override
    public int processFormField(FileItem item) {
        String fileName = item.getFieldName();
        //获得字段id并返回
        String value = item.getString();
        try {
            value = item.getString("UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        return Integer.parseInt(value);
    }

    /**
     * 将附件字段放在本地中
     *
     * @param fileItem 含附件信息的item字段
     * @param request  request
     * @return 执行结果
     */
    @Override
    public Result processFileUpload(FileItem fileItem, HttpServletRequest request) {
        //上传的文件名
        String fileName = fileItem.getName();
        if (fileName != null) {
            fileName = FilenameUtils.getName(fileName);
            //时间戳加文件名，防止文件名重复
            fileName = new Date().getTime() + "_" + fileName;
        }
        //存放路径
        String realPath = request.getServletContext().getRealPath("/files");
        System.out.println(realPath);
        //子目录
        String childDirectory = genChildDirectory(realPath);
        System.out.println(realPath + File.separator + childDirectory);
        //生成完整的存放路径
        File storeDirectory = new File(realPath + File.separator + childDirectory);
        if (!storeDirectory.exists()) {
            storeDirectory.mkdirs();
        }
        try {
            fileItem.write(new File(storeDirectory, fileName));
            //返回文件的地址值，用于展示
            System.out.println("./files/" + genChildDirectory("./files") + "/" + fileName);
            return Result.result("./files/" + genChildDirectory("./files") + "/" + fileName);
        } catch (Exception e) {
            return Result.noResult();
        }

    }

    /**
     * 添加进附件表
     *
     * @param articleId 文章id
     * @param url       附件在本地的连接
     * @return 主键
     */
    @Override
    public int articleImageUpload(Integer articleId, String url) throws SQLException, InterruptedException, IllegalAccessException {
        System.out.println("执行了！");
        return FILES_DAO.insertFiles(new Files(null, url, articleId));

    }

    /**
     * 将文件路径加上时间戳，防止不能刷新
     *
     * @param realPath 文件路径
     * @return 文件路径+时间戳
     */
    public static String genChildDirectory(String realPath) {
        Date now = new Date();
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String str = df.format(now);
        //创建文件夹
        File file = new File(realPath, str);
        if (!file.exists()) {
            file.mkdirs();
        }
        return str;
    }
}
